<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
 * Created on 2012-7-5
 *
 * 用户管理
 */
class Users extends MY_ADMIN_Controller{

	function __construct()
	{
		parent::__construct();
		$this->loadModel('User_model','User');
	}
	
	/**
	 * 后台用户管理首页（用户列表）
	 */
	function index(){
		$like = $this->_searchLike($this->User);
		$where = $this->_searchWhere($this->User);
		$map = array();
		if(!empty($like)) $map['like'] = $like;
		if(!empty($where)) $map['where'] = $where;
		$this->assign['result'] = $this->getPager($this->User,$map);
		//print_r($this->getPager($this->User,$map));exit;
		$this->display();
	}
	
	/**
	 * 登录
	 */
	function login(){
		$redirect = getRedirect(site_url('admin/home'));
		if(!empty($_POST)){
			$data = $this->input->post(null,true);
			$user = $this->User->doLoginByUserName($data['username'],$data['password'],true);
			if($user!==false){
				$newdata['id']		= $user->id;
				$newdata['truename']	= $user->username;
				$newdata['username']	= $user->username;
				$newdata['is_admin']	= $user->is_admin;
				if(!empty($user->role_ids)) $newdata['roles']	= $user->role_ids==1?1:explode(',',$user->role_ids);
				//记住我
				if(isset($data['rememberme']) && $data['rememberme']=='forever'){
					$this->config->set_item('sess_expiration', 0);
				}
				$this->session->set_userdata($newdata);
				$mes = 'mes_success';
				return $this->showMessage($mes,$redirect);
			}else{
				return $this->showMessage($this->User->_error); 
			}
		}
		
		$this->display('users/login',array('redirect'=>$redirect));
	}

	/**
	 * 退出
	 */
	function logout(){
		$this->session->sess_destroy();
		$redirect = $this->config->item('system_login_url');
		$mes = 'mes_success';
		return $this->showMessage($mes,$redirect);
	}
	
	function create(){
		//$this->lang->load('template');
		if($this->input->post(null,true)){
			return $this->save('users/create');
		}else{
			$this->display();
		}
	}
	
	/**
	 * 编辑用户
	 */
	function edit($userId){
		if($this->input->post(null,true)){
			return $this->save('users/edit');
		}else{
			$res = $this->User->findByUserId($userId);
			if(empty($res)){
				return $this->showMessage('error_param',site_url('admin/users'));
			}
			$this->assign['user'] = $res;
			$userRoles = array();
			if(!empty($res['roles'])){
				$userRoles = explode(',',$res['roles']);
			}
			$this->assign['userRoles'] = $userRoles;
			$this->display();
		}
	}	
	/**
	 * 添加用户
	 */
	private function save( $type='' ){
		$redirect = getRedirect(base_url('admin/users'));
		$this->load->library('form_validation');
		$this->lang->load('template');
		
		if ($this->form_validation->run($type) == FALSE){
			return $this->showMessage(validation_errors()); 
		}
		//if isset user roles
		if(isset($_POST['roles'])){
			$_POST['roles'] = implode(',',$_POST['roles']);
		}
		
		if(($user_id = $this->User->save($this->input->post(null,true)))!==false){
			$mes = 'mes_success';
			return $this->showMessage($mes,$redirect);
		}else{
			return $this->showMessage($this->User->_error); 
		}
	}
	
	function check($value,$field){
		$where = array(
			$field=>$value,
		);
		$result = $this->User->findByField($where);
		$currrId = $this->input->post('id',true);
		if(!empty($result)&& $result[0]['id']!=$currrId){
			$this->form_validation->set_message('check', 'The %s field has existing');
			return false;
		}
		return true;
	}
	
	function changepwd(){
		if(!empty($_POST['password'])){
			$redirect = $this->getRedirect('user_changepwd');
			$rules['curPwd']	= "trim|required|min_length[5]|max_length[12]";
			$rules['password']	= "trim|required|matches[passwordConfirm]|min_length[5]|max_length[12]";
			if ($this->validation($rules,'user') == FALSE)
			{
				$this->showMessage($this->validation->error_string); 
			}

			// Validate if the password of current user is correct?
			$res = $this->User->findByUserId($this->curUser['id']);
			if(!empty($res)&&($res['password']==crypt($_POST['curPwd'],$res['salt']))){
				$data = $res;
				$data['password'] = $_POST['password'];
				if($_POST['curPwd']!=$_POST['password']){
					if($this->User->save($data)===false){
						$this->showMessage($this->User->_error);
					}
				}
				$mes = 'mes_success';
				$this->showMessage($mes,$redirect);
			}else{
				$this->showMessage('error_pwd_wrong',$redirect);
			}
		}
		$this->display();
	}


	function remove($id){
		$id = $id>0?$id:intval($this->input->get('id',true));
		$res = $this->User->findByUserId($id);
		if(empty($res)){
			return $this->showMessage('error_param',site_url('admin/users'));
		}
		if($this->User->removeByPks($id) === true){
			$mes = 'mes_success';
			return $this->showMessage($mes,site_url('admin/users'));
		}
		return $this->showMessage('failure',site_url('admin/users'));
	}

	protected function getAllRoles(){
		$this->load->model('Role');
		$this->assign['roles'] =  $this->Role->findAll();
	}
}
/* End of file users.php */
/* Location: ./application/controllers/users.php */